package main

import (
	"fmt"
	"gin-gateway/example/gateway_demo/otherProxy/grpc_interceptor"
	proxy2 "gin-gateway/example/gateway_demo/otherProxy/proxy"
	"gin-gateway/example/gateway_demo/otherProxy/public"
	"google.golang.org/grpc"
	"log"
	"net"
	"time"
	"gin-gateway/example/gateway_demo/otherProxy/load_balance"
	"google.golang.org/grpc/encoding"
	"gin-gateway/example/gateway_demo/otherProxy/grpc_proxy"
)

const port = ":50051"

// 负载均衡 + 流量统计 +
func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	lb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin)
	lb.Add("127.0.0.1:50055", "40")
	encoding.RegisterCodec(grpc_proxy.Codec()) // 设置grpcServer 全局使用编解码

	counter, _ := public.NewFlowCountService("local_app", time.Second)
	grpcHandler := proxy2.NewGrpcLoadBalanceHandler(lb)
	s := grpc.NewServer(
		grpc.ChainStreamInterceptor(grpc_interceptor.GrpcAuthStreamInterceptor, grpc_interceptor.GrpcFlowCountStreamInterceptor(counter)),
		grpc.UnknownServiceHandler(grpcHandler)) // 默认都是流式方法 ， 一元方法不起作用

	fmt.Printf("server listening at %v\n", lis.Addr())
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
